from datetime import datetime, timedelta 
from concurrent.futures import ThreadPoolExecutor

import logging, requests, wqAPI

wqAPI.init_logging()

expire_Time = datetime.min
expire_Span = 3.5
sess = requests.session()
checkWorkers = 5 #check with 5 threads.

def get_session():  #get or update the session with timespan:
    global sess, expire_Time  # 声明要修改的全局变量
    current_time = datetime.now()  
    # 若session未初始化或已过期，重新登录  
    if (sess.auth is None) or (current_time >= expire_Time):
        sess = wqAPI.sign_in()  
        expire_Time = current_time + timedelta(hours=expire_Span)  
    return sess

sess = get_session()

logging.info(f"Scanning Unsubmitted Alphas...")
limit = 100
startIdx = 0
sharpe=""  #condition like: >=1.25
result = wqAPI.getAlphaList(sess, sharpeMin=sharpe, limit=limit, startIdx=startIdx).json()
next = result["next"]
total = 0 #result["count"] //will have new alphas in the process.
validCount = 0

logging.info(f"Scan found Alphas: {result['count']}, start check status...")

def checkAndUpdateAlpha(alpha):
    hasFail = any(check["result"] == "FAIL" for check in alpha["is"]["checks"])
    alphaId = alpha["id"]
    valid = False
    color = alpha["color"]

    if color == "BLUE": #before items mark as valid... avoid due to some reason auto hide
        validCount += 1
        valid = True
    else: 
        if hasFail :
            #Set color RED, and hide the alpha
            wqAPI.pathAlpha(get_session(), alphaId, {"hidden": True,"color": "RED"})
        else:
            valid = wqAPI.checkAlpha(sess, alphaId)
            if not valid:
                wqAPI.pathAlpha(get_session(), alphaId, {"hidden": True,"color": "BLUE"})
            else:
                validCount += 1
                wqAPI.pathAlpha(get_session(), alphaId, {"color": "YELLOW"})
                #TODO:some want auto-submit, need captre the submit API.
                #wqAPI.submitAlpha(get_session(), alphaId, {"name": alpha["regular"]["code"]})

    if not hasFail:  # reduce failed output...
        logging.info(f"Alpha: {alphaId}, Failed: {hasFail}, Valid: {valid}")

while True:
    with ThreadPoolExecutor(max_workers=checkWorkers) as executor:
        for alpha in result["results"] :
            executor.submit(checkAndUpdateAlpha, alpha)

    startIdx = validCount
    total += len(result["results"])
    logging.info(f"Scanned: {total} Valid count: {validCount}")

    #check if have next phase
    if next is None :
        break

    #due to hide, the scope changed, so always start with offset 0.
    #but due to valid exist, skip the validCount. now getlist order by createDate.
    #head of the list contains validCount items, new items, always on tail of the list.
    result = wqAPI.getAlphaList(sess,sharpeMin=sharpe,limit=limit, startIdx=startIdx).json()
    next = result["next"]
    logging.info(f"Proceeding to next requst, scan found total: {result['count']}")


logging.info(f"Unsubmitted Alphas scanned {total} (Valid: {validCount})")